//
//  ComposeViewController.m
//  kuangjia
//
//  Created by 张帅 on 15/10/6.
//  Copyright © 2015年 ZhangShuai. All rights reserved.
//

#import "ComposeViewController.h"
#import "UILabel+Contenlable.h"
#import "UserAccountViewModel.h"
#import "UIButton+bottom.h"
#import "PictureSelectorViewController.h"

#import "EmoticonViewController.h"
#import "FSEmoticonModel.h"

#import "FSEmoticonViewModel.h"
#import "EmoticonAttachment.h"

#import "UITextView+extension.h"

#import "NetworkTools.h"
#import <SVProgressHUD.h>

#define HMMaxPictureCount  9
@interface ComposeViewController ()<UITextViewDelegate>

@property(nonatomic,strong) UIToolbar *toobar;

@property(nonatomic,strong) UILabel *placeholderLabel;

@property(nonatomic,strong) PictureSelectorViewController *pictureSelectorVC;
@property(nonatomic,strong) UITextView *textView;

@property(nonatomic,strong) NSLayoutConstraint *toolbarBottomCons;

@property(nonatomic,strong) NSLayoutConstraint *textViewBottomCons;
@property(nonatomic,strong) NSLayoutConstraint *pictureViewHeightCons1;

@property(nonatomic,strong) EmoticonViewController *keyboardVC;


@end

@implementation ComposeViewController


-(EmoticonViewController *)keyboardVC{
    
    
    if (_keyboardVC==nil) {
        
        _keyboardVC=[[EmoticonViewController alloc] init];
        
        __weak __typeof(self)wself = self;
        
        
        _keyboardVC.selectedEmoticonCallBack = ^(FSEmoticonModel *emotion){
            [wself.textView insertEmoticon:emotion ];
            
        };
    }
    
     return   _keyboardVC;
}



-(void)switchEmoticonKeyboard{

    [self.textView resignFirstResponder];
    
    self.textView.inputView = (self.textView.inputView==nil)? self.keyboardVC.view:nil;
      // 激活焦点
    
    
    [self.textView becomeFirstResponder];
    

}
-(void)loadView{

    self.view = [[UIView alloc] init];
    
       // 将自动调整 scrollView 的缩进取消
    
    self.automaticallyAdjustsScrollViewInsets =NO;
    
    
    self.view.backgroundColor =[UIColor whiteColor];
    [self prepareNav];
    
    [self prepareToolBar];
    
    [self prepareTextView];
    
    [self preparePictureView];
    
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    if (self.pictureViewHeightCons1.constant ==0) {
        
        [self.textView becomeFirstResponder];
    }
}


-(void)viewDidLoad{
  [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChanged:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    
}

-(void)keyboardChanged:(NSNotification*)notification{
//    NSLog(@"n%@",notification);

    // 获取最终的frame － OC 中将结构体保存在字典中，存成 NSValue
    // 获取最终的frame － OC 中将结构体保存在字典中，存成 NSValue
  
    
//    NSInteger  curve = [notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
//      // 获取最终的frame － OC 中将结构体保存在字典中，存成 NSValue
//    
//    CGRect rect  = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];

    
    NSDictionary *dict =notification.userInfo;
    
    CGFloat keyboardOffsetY= [dict[UIKeyboardFrameEndUserInfoKey]CGRectValue ].origin.y;
    
    CGFloat duration = [dict[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    self.toolbarBottomCons.constant =-[UIScreen mainScreen].bounds.size.height +keyboardOffsetY;
    
    [UIView animateWithDuration:duration animations:^{
        
          [self.view layoutIfNeeded];
    }];

}

-(void)dealloc{
  // 注销通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];

}


-(void)textViewDidChange:(UITextView *)textView{

    
    self.placeholderLabel.hidden=textView.hasText;
    
    self.navigationItem.rightBarButtonItem.enabled = textView.hasText;

}


-(void)preparePictureView{
    // 0. 添加子控制器 － 提示：实际开发中发现响应者链条无法正常传递，通常就是忘记添加子控制器
    // storyboard 中有一个 containerView，纯代码中没有这个控件
    // 本质上就是一个 UIView
    // 1> addSubView(vc.view)
    // 2> addChildViewController(vc)

    [self addChildViewController:self.pictureSelectorVC];
    
       // 1. 添加视图
    
//    [self.view addSubview:self.pictureSelectorVC.view];
    [self.view insertSubview:self.pictureSelectorVC.view belowSubview:self.toobar];
    
    // 2. 自动布局
    
    CGSize  size =  [UIScreen mainScreen].bounds.size;
    
    CGFloat w = size.width;
    CGFloat h = 0;
    
    
    self.pictureSelectorVC.view.translatesAutoresizingMaskIntoConstraints  =NO;
    
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.pictureSelectorVC.view attribute:(NSLayoutAttributeLeft) relatedBy:(NSLayoutRelationEqual) toItem:self.view attribute:(NSLayoutAttributeLeft) multiplier:1 constant:0]];
    
    
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.pictureSelectorVC.view attribute:(NSLayoutAttributeBottom) relatedBy:(NSLayoutRelationEqual) toItem:self.view attribute:(NSLayoutAttributeBottom) multiplier:1 constant:0]];
    
    
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.pictureSelectorVC.view attribute:(NSLayoutAttributeWidth) relatedBy:(NSLayoutRelationEqual) toItem:nil attribute:(NSLayoutAttributeWidth) multiplier:1 constant:w]];
    
    
    
    self.pictureViewHeightCons1 =[NSLayoutConstraint constraintWithItem:self.pictureSelectorVC.view attribute:(NSLayoutAttributeHeight) relatedBy:(NSLayoutRelationEqual) toItem:nil attribute:(NSLayoutAttributeHeight) multiplier:1 constant:h];
    
    
    [self.view addConstraint:self.pictureViewHeightCons1];

    
  
    
    
}

-(void)prepareTextView{
    [self.view addSubview:self.textView];

    self.textView.translatesAutoresizingMaskIntoConstraints = NO;

    self.toobar.translatesAutoresizingMaskIntoConstraints=NO;
    NSDictionary *dict =@{@"top":self.topLayoutGuide,@"tb":self.toobar,@"tv":self.textView}
    ;
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[tv]-0-|" options:0 metrics:nil views:dict]];
    
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[top]-0-[tv]" options:0 metrics:nil views:dict]];
    
    self.textViewBottomCons = [NSLayoutConstraint constraintWithItem:self.textView attribute:(NSLayoutAttributeBottom) relatedBy:(NSLayoutRelationEqual) toItem:self.toobar attribute:(NSLayoutAttributeTop) multiplier:1 constant:0];
    
    
    [self.view addConstraint:self.textViewBottomCons];
    
    
    
    // 设置占位标签 － 添加到 textView 就是为了保证能够同时滚动

    [self.textView addSubview:self.placeholderLabel];
    
    self.placeholderLabel.frame =CGRectMake(5, 8, self.placeholderLabel.bounds.size.width, self.placeholderLabel.bounds.size.height);
    
    

}
-(void)prepareToolBar{
  
    [self.view addSubview:self.toobar];
    
    [self.toobar setBackgroundColor:[UIColor colorWithWhite:0.8 alpha:1]];
    
       // 设置自动布局
    
    
    CGFloat with=[UIScreen mainScreen].bounds.size.width;
    
    self.toobar.translatesAutoresizingMaskIntoConstraints=NO;
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.toobar attribute:(NSLayoutAttributeLeft) relatedBy:(NSLayoutRelationEqual) toItem:self.view attribute:(NSLayoutAttributeLeft) multiplier:1 constant:0]];
    
  
    self.toolbarBottomCons =[NSLayoutConstraint constraintWithItem:self.toobar attribute:(NSLayoutAttributeBottom) relatedBy:(NSLayoutRelationEqual) toItem:self.view attribute:(NSLayoutAttributeBottom) multiplier:1 constant:0];
    
    [self.view addConstraint:self.toolbarBottomCons];
    
    
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.toobar attribute:(NSLayoutAttributeWidth) relatedBy:(NSLayoutRelationEqual) toItem:nil attribute:(NSLayoutAttributeWidth) multiplier:1 constant:with]];
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.toobar attribute:(NSLayoutAttributeHeight) relatedBy:(NSLayoutRelationEqual) toItem:nil attribute:(NSLayoutAttributeHeight) multiplier:1 constant:44]];
    
      // 定义按钮数组
    
 

}




-(void)prepareNav{

    
    self.navigationItem.leftBarButtonItem =  [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(closeClick)];
    
    self.navigationItem.rightBarButtonItem =  [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(sendStatus)];
    
    self.navigationItem.backBarButtonItem.enabled=NO;
    
     // 标题视图
    UIView *titleView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 32)];
    

      UILabel *titleLabel =[[UILabel alloc] initWithTitle:@"发微博" color:[UIColor purpleColor] sizeFont:14];
    
     UILabel *nameLable =[[UILabel alloc] initWithTitle:[[[UserAccountViewModel sharedUserAccount]userAccount]name] color:[UIColor darkGrayColor] sizeFont:14];
    
    [titleView addSubview:titleLabel];
    [titleView addSubview:nameLable];
      
    
    titleLabel.translatesAutoresizingMaskIntoConstraints=NO;
    nameLable.translatesAutoresizingMaskIntoConstraints=NO;
    
    
    [titleView addConstraint:[NSLayoutConstraint constraintWithItem:titleLabel attribute:(NSLayoutAttributeCenterX) relatedBy:(NSLayoutRelationEqual) toItem:titleView attribute:(NSLayoutAttributeCenterX) multiplier:1 constant:0]];

    
    [titleView addConstraint:[NSLayoutConstraint constraintWithItem:titleLabel attribute:(NSLayoutAttributeTop) relatedBy:(NSLayoutRelationEqual) toItem:titleView attribute:(NSLayoutAttributeTop) multiplier:1 constant:0]];
    
    
    
    [titleView addConstraint:[NSLayoutConstraint constraintWithItem:nameLable attribute:(NSLayoutAttributeCenterX) relatedBy:(NSLayoutRelationEqual) toItem:titleView attribute:(NSLayoutAttributeCenterX) multiplier:1 constant:0]];

    
    [titleView addConstraint:[NSLayoutConstraint constraintWithItem:nameLable attribute:(NSLayoutAttributeBottom) relatedBy:(NSLayoutRelationEqual) toItem:titleView attribute:(NSLayoutAttributeBottom) multiplier:1 constant:0]];

    
    self.navigationItem.titleView=titleView;
}


-(PictureSelectorViewController *)pictureSelectorVC{

    if (_pictureSelectorVC==nil) {
        
        _pictureSelectorVC = [[PictureSelectorViewController alloc] init];
        
    }
    return _pictureSelectorVC;
}
-(UILabel *)placeholderLabel{

    if (_placeholderLabel==nil) {
        _placeholderLabel=[[UILabel alloc] initWithTitle:@"分享新鲜事..." color: [UIColor darkGrayColor]sizeFont:18];
    }
 
    return _placeholderLabel
    ;
}
-(void)sendStatus{
    NSLog(@"发微博");
    
    NSString *text =[self.textView emoticonText];

 
    
    if ( text.length > HMMaxPictureCount) {
        
        [SVProgressHUD showErrorWithStatus:@"你输入的文字过长" maskType:SVProgressHUDMaskTypeBlack];
        
        return;
    }
    
    UIImage *image= self.pictureSelectorVC.pictures.lastObject;
    
    [[[NetworkTools sharedTools]sendStatus:text image: image] subscribeNext:^(id result) {
    
    NSLog(@"result--------%@",result);
} error:^(NSError *error) {
    
    NSLog(@"%@",error);
    
    [SVProgressHUD showErrorWithStatus:@"您的网络不给力"];
    
    
} completed:^{
    
    [self closeClick];
    
}];
    
  
}

-(void)closeClick{
    
    
    [self.textView resignFirstResponder];
    
    [self dismissViewControllerAnimated:YES completion:nil];
    NSLog(@"取消");

    
}
-(void)selectPicture{
    
    [self.view removeConstraint:self.textViewBottomCons];
    
    
    self.textViewBottomCons = [NSLayoutConstraint constraintWithItem:self.textView attribute:(NSLayoutAttributeBottom) relatedBy:(NSLayoutRelationEqual) toItem:self.pictureSelectorVC.view attribute:(NSLayoutAttributeTop) multiplier:1 constant:0];
  
    
    [self.view addConstraint:self.textViewBottomCons];
    
    // 3. 设置高度约束

    self.pictureViewHeightCons1.constant  =[UIScreen mainScreen].bounds.size.height* 0.6;
    
    [self.textView resignFirstResponder];
    
    [UIView animateWithDuration:1 animations:^{
       
        [self.view layoutIfNeeded];
    }];
    
 
//    PictureSelectorViewController *vc = [[PictureSelectorViewController alloc] init];
//    
//  [self presentViewController:vc animated:YES completion:nil];
//    NSLog(@"selectPicture");
//    
}

-(void)showEmoticonKeyboard{
    
    NSLog(@"showEmoticonKeyboard");
    
}


-(UITextView *)textView{
    if (_textView==nil) {
        
        _textView=[[UITextView alloc] init];
        
        _textView.font=[UIFont systemFontOfSize:18];
        
        _textView.textColor = [UIColor darkGrayColor];
        
        _textView.delegate=self;
        // 允许垂直拖拽
        
        _textView.keyboardDismissMode=UIScrollViewKeyboardDismissModeOnDrag;
        _textView.alwaysBounceVertical=YES;
        
    }
    return _textView;
}



-(UIToolbar *)toobar{
    if (!_toobar) {
        _toobar = [[UIToolbar alloc] init];
        UIBarButtonItem* spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemFlexibleSpace)target:nil action:nil];
        
        NSArray* btnArray = @[ [UIButton buttonWithImageName:@"compose_toolbar_picture" Target:self selector:@selector(selectPicture)],
                               [UIButton buttonWithImageName:@"compose_mentionbutton_background"
                                                      Target:self
                                                    selector:nil],
                               [UIButton buttonWithImageName:@"compose_emoticonbutton_background"
                                                      Target:self
                                                    selector:@selector(switchEmoticonKeyboard)],
                               [UIButton buttonWithImageName:@"compose_trendbutton_background"
                                                      Target:self
                                                    selector:nil],
                               [UIButton buttonWithImageName:@"compose_addbutton_background"
                                                      Target:self
                                                    selector:nil] ];
        
        NSMutableArray* barItems = [NSMutableArray array];
        for (UIButton* btn in btnArray) {
            UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithCustomView:btn];
            [barItems addObject:item];
            [barItems addObject:spaceItem];
        }
        [barItems removeLastObject];
        
        _toobar.items = barItems.copy;
    }
    return _toobar;
    
}


@end
